# dev.setupMiddlewares

- **Type:**

```ts
type SetupMiddlewaresServer = {
  sockWrite: (
    type: string,
    data?: string | boolean | Record<string, any>,
  ) => void;
  environments: EnvironmentAPI;
};

type SetupMiddlewares = Array<
  (
    middlewares: {
      unshift: (...handlers: RequestHandler[]) => void;
      push: (...handlers: RequestHandler[]) => void;
    },
    server: SetupMiddlewaresServer,
  ) => void
>;
```

- **Default:** `undefined`

Provides the ability to execute a custom function and apply custom middleware.

> See [Dev Server - Middleware](/guide/basic/server#middleware) for more information.

## Execution order

The order among several different types of middleware is: `unshift` => internal middleware => `push`.

```ts title="rsbuild.config.ts"
export default {
  dev: {
    setupMiddlewares: [
      (middlewares, server) => {
        middlewares.unshift((req, res, next) => {
          console.log('first');
          next();
        });

        middlewares.push((req, res, next) => {
          console.log('last');
          next();
        });
      },
    ],
  },
};
```

## Server API

In the `setupMiddlewares` function, you can access the `server` object, which provides some server APIs.

### environments

Provides Rsbuild's [environment API](/api/javascript-api/environment-api#environment-api), see [Dev server API - environments](/api/javascript-api/dev-server-api#environments) for more details.

```ts title="rsbuild.config.ts"
export default {
  dev: {
    setupMiddlewares: [
      (middlewares, { environments }) => {
        middlewares.unshift(async (req, _res, next) => {
          const webStats = await environments.web.getStats();
          console.log(webStats.toJson({ all: false }));
          next();
        });
      },
    ],
  },
};
```

### sockWrite

Sends some message to HMR client, see [Dev server API - sockWrite](/api/javascript-api/dev-server-api#sockwrite) for more details.

For example, if you send a `'static-changed'` message, the page will reload.

```ts title="rsbuild.config.ts"
export default {
  dev: {
    setupMiddlewares: [
      (middlewares, { sockWrite }) => {
        if (someCondition) {
          sockWrite('static-changed');
        }
      },
    ],
  },
};
```
